package p.ithorns.sample.office.example;

import cn.hutool.core.date.DateUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import p.ithorns.sample.office.excel.ComplexExcelService;
import p.ithorns.tools.excel.EasyExcelUtil;
import p.ithorns.tools.excel.model.ImportRecordBody;
import p.ithorns.tools.excel.model.ImportSheetResult;
import p.ithorns.tools.excel.read.BaseImportHandler;
import p.ithorns.tools.excel.write.SingleSheetExporter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * MainController
 *
 * @author HtL
 * @date 2024/7/17 16:48
 * @since 1.0.0
 */
@RequestMapping("/excel")
@RestController
public class ExcelController {

    @Resource
    private ComplexExcelService service;
    @PostMapping(value = "/complex-head/import")
    public void test(MultipartFile file) {
        service.doImport(file);
    }
    /**
     * 模版
     */
    @GetMapping(value = "/template")
    public void getExcelTemplate(HttpServletResponse response) throws IOException {
        EasyExcelUtil.template(response, "User", UserImportXls.class);
    }

    /**
     * 导入
     */
    @PostMapping(value = "/import")
    public ImportSheetResult<?> importRole(MultipartFile file) throws IOException {
        ImportSheetResult<UserImportXls> importResult = EasyExcelUtil.doImport(file, importHandler);

        // 导入记录
        ImportRecordBody body = new  ImportRecordBody();
        body.setModule("USER");
        body.setImportTime(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
        body.setSuccessCount(importResult.getSuccessCount());
        body.setFailCount(importResult.getErrorCount());

        // 源文件
        body.setSourceFile(file);

        // 错误文件
        MultipartFile errorFile = SingleSheetExporter.createErrorMultipartFile(importResult);
        if (null != errorFile) {
            body.setErrorFile(errorFile);
        }

        // 存储导入记录 saveImportRecord(body);
        return importResult;
    }

    private final BaseImportHandler<UserImportXls> importHandler = new BaseImportHandler<UserImportXls>() {

        @Override
        public String getSheetName() {
            return "User";
        }

        @Override
        public void saveToDb(List<UserImportXls> imports) {
            System.out.println("Do Save Users: " + imports);
        }
    };

}